<template>
  <div class="goodsinfo-container">
    <div class="empty-con" v-if="isEmpry">
      <div class="empty-text">商品已下架 看看其他吧</div>
    </div>
    <div v-else>
      <!-- 实现动画的小球 -->
      <!-- 注意：钩子函数动画，钩子函数都是通过事件绑定机制，绑定到transition元素上的 -->
      <transition
        @before-enter="beforeEnter"
        @enter="enter"
        @after-enter="afterEnter"
      >
        <div class="ball" v-show="flag"></div>
      </transition>
      <!-- 轮播图区域 -->
      <div class="mui-card">
        <div class="mui-card-content">
          <div class="mui-card-content-inner">
            <swiper :lunbotu="lunbotu" :imgname="'src'"></swiper>
          </div>
        </div>
      </div>
      <!-- 商品购买区域 -->
      <div class="mui-card">
        <div class="mui-card-header">{{ goodsinfo.title }}</div>
        <div class="mui-card-content">
          <div class="mui-card-content-inner">
            <p class="price">
              市场价：
              <span style="margin-right: 10px"
                ><del>￥{{ goodsinfo.market_price }}</del></span
              >
              销售价：
              <span style="font-size: 16px; color: red; font-weight: bold"
                >￥{{ goodsinfo.sell_price }}</span
              >
            </p>
            <div
              class="discount"
              @click="popupVisible = true"
              v-if="!isEmptyDiscount"
            >
              <div style="color: #8f8f94">优惠</div>
              <div class="ticket">
                {{ firstDiscount }}
              </div>
              <div style="color: #3b3b3b">领券</div>
            </div>
            <mt-popup v-model="popupVisible" position="bottom">
              <div class="discount-detail">
                <div class="top-con">
                  <div class="title">领取优惠券</div>
                  <div style="color: #8f8f94" @click="popupVisible = false">
                    X
                  </div>
                </div>
                <div v-for="(item, index) in discountList" :key="index">
                  <div class="block" v-if="!item.isEmpty">
                    <div class="img">
                      <div style="font-size: 18px">￥{{ item.sub }}</div>
                      <div>立减</div>
                    </div>
                    <div class="block-detail">
                      <div>
                        <div style="color: #3b3b3b">
                          {{ item.discount }}
                        </div>
                      </div>
                      <div
                        style="color: #ff8a9e"
                        v-if="item.get == 1"
                        @click="popupVisible = false"
                      >
                        去使用
                      </div>
                      <div
                        style="color: #ff8a9e"
                        @click="getTicket(index, item)"
                        v-if="item.get == 0"
                      >
                        立即领取
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </mt-popup>
            <p>
              购买数量：
              <!-- 注：这里的max是库存量 -->
              <!-- 动态变量就undefine,写死就可以，因为Ajax获取数据（异步请求）需要时间 -->
              <nobox
                :max="goodsinfo.stock_quantity"
                @func="getSelectedCount"
              ></nobox>
            </p>
            <div class="operate">
              <mt-button
                type="primary"
                @click="createOrderNo"
                style="margin-right: 10px"  
                >立即购买</mt-button
              >
              <mt-button type="danger" @click="addToCart">加入购物车</mt-button>
              <div class="my-like-con" @click="changeLike">
                <img
                  src="../../assets/img/liked.png"
                  alt=""
                  width="25px"
                  v-if="isLiked"
                />
                <img
                  src="../../assets/img/like.png"
                  alt=""
                  width="25px"
                  v-else
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 商品参数区域 -->
      <div class="mui-card">
        <div class="mui-card-header">商品参数</div>
        <div class="mui-card-content">
          <div class="mui-card-content-inner">
            <p>商品货号：{{ goodsinfo.goods_no }}</p>
            <p>库存情况：{{ goodsinfo.stock_quantity }}件</p>
            <p>上架时间：{{ goodsinfo.add_time | dataFormat }}</p>
            <p>
              商品摘要：<span style="color: black">{{
                goodsinfo.zhaiyao
              }}</span>
            </p>
          </div>
        </div>
        <div class="mui-card-footern btnarea">
          <!-- <router-link :to="'/home/goodsdesc/'+goodsinfo.id">
                    <mt-button type="primary" size="large" plain>图文介绍</mt-button>
                </router-link> -->

          <!-- 使用编程式导航（使用JS代码的方式），来实现路由页面的跳转 -->
          <!-- 元素导航：使用router-link元素实现的导航 -->
          <mt-button type="primary" size="large" plain @click="goDesc"
            >图文介绍</mt-button
          >
          <mt-button type="danger" size="large" plain @click="goComment"
            >商品评论</mt-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 导入自己封装的轮播图组件
import swiper from "../sub-components/Swiper.vue";
// 导入数字框组件
import nobox from "../sub-components/GoodsInfo_nobox.vue";
import moment from "moment";
import { mapMutations } from "vuex";
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      popupVisible: false,
      isEmpry: false,
      lunbotu: [],
      goodsinfo: {},
      discountList: [],
      firstDiscount: "",
      useStatusList: [],
      isEmptyDiscount: true,
      likeId: "",
      isLiked: false,
      flag: false, //小球的显示与隐藏
      selectedCount: 1, //用户选择的商品购买数量，默认选中一个商品
    };
  },
  props: ["id"],
  components: {
    swiper,
    nobox,
  },
  created() {
    if (localStorage.getItem("UserInfo")) {
      this.username = window.JSON.parse(
        localStorage.getItem("UserInfo")
      ).username;
    }
  },
  activated() {
    this.selectedCount = 1;
    this.isLiked = false;
    this.getGoodsInfoById();
    this.getMyLike();
  },
  methods: {
    getGoodsInfoById() {
      if (this.id == 0) {
        this.isEmpry = true;
      } else {
        this.$http
          .get("/getGoodsInfo", {
            params: {
              id: this.id,
            },
          })
          .then((res) => {
            if (res.data.errcode === 200) {
              let data = res.data.message[0];
              if (
                data.length == 0 ||
                data.stock_quantity < 0 ||
                data.stock_quantity == 0
              ) {
                // 商品下架-》删除商品
                this.isEmpry = true;
              } else {
                this.goodsinfo = data;
                this.getMyDiscountStatus();
                this.isEmpry = false;
              }
              this.discountList = [];
              let arr2 = [];
              arr2 = data.discount.split(",");
              // 如果要检索的字符串值没有出现，则该方法返回 -1。
              arr2.forEach((item, index) => {
                // 字符串包含'减'
                if (item.indexOf("减") != -1) {
                  let arr = item.split("减");
                  let limitIndex = arr[0].indexOf("满") + 1;
                  this.discountList.push({
                    discount: item,
                    limit: arr[0].substring(limitIndex),
                    sub: arr[1],
                    get: 0,
                  });
                } else {
                  this.discountList.push({
                    discount: item,
                    limit: 0,
                    sub: item.substring(0, 1),
                    get: 0,
                  });
                }
              });
              this.firstDiscount = this.discountList[0].discount;
              this.lunbotu = data.src.split(",");
            } else {
              this.isEmpry = true;
            }
          });
      }
    },
    getMyDiscountStatus() {
      this.$http
        .get("/getMyDiscountStatus", {
          params: {
            username: this.username,
            goods_id: this.goodsinfo.id,
          },
        })
        .then((res) => {
          if (res.data.errcode === 200) {
            let data = res.data.message;
            let noUse = true; //代表还没用完券
            // 判断用户是否已经用完全部优惠券，或者一张优惠券都没领取.
            let i = 0;
            data.forEach((item, index) => {
              // 有一张优惠券，且用完了,或者有多张优惠券
              if (
                (data.length == 1 && i == 1) ||
                (data.length > 1 && i == data.length - 1)
              ) {
                noUse = false;
              }
              if (item.use_status == 2) {
                i++;
                this.discountList[index].isEmpty = true;
              }
            });
            this.useStatusList = [];
            // 说明该用户还有没有使用的优惠券,当使用用户券后状态变成0
            if (noUse) {
              data.forEach((item) => {
                if (item.use_status == 1) {
                  this.useStatusList.push(item);
                }
              });
              this.useStatusList.forEach((item, index) => {
                this.discountList[index].get = item.use_status;
              });
              this.isEmptyDiscount = false;
            } else {
              // 如果该商品用户都使用完优惠券了，则对该用户隐藏优惠券
              this.useStatusList = [];
              this.isEmptyDiscount = true;
            }
          } else {
            this.useStatusList = [];
          }
        });
    },
    goDesc() {
      //点击按钮跳转到商品的描述页面
      // 注意：在this组件上，有this.$route(专门来获取路由中参数的)和this.$router（专门实现编程式导航的）【go(-1)往后跳转一页】
      // this.$router.push("/idssp/shops/goodsdesc/"+this.goodsinfo.id)
      this.$router.push("/idssp/shops/goodsdesc/" + this.goodsinfo.id);
    },
    goComment() {
      // this.$router.push("/home/goodscomment/"+this.goodsinfo.id)
      // 方式二：取名字传
      this.$router.push({
        name: "goodscmt",
        params: { id: this.goodsinfo.id, title: this.goodsinfo.title },
      });
    },
    ...mapMutations(["addToCar"]),
    addToCart() {
      // 如何根据我的价格匹配最合适的优惠券呢？ 0<x<50  -5  50<x<100  -8  x>100 -15
      let totalPrice = this.selectedCount * this.goodsinfo.sell_price;
      let discount = 0;
      this.useStatusList.forEach((item) => {
        if (totalPrice > item.limit_num) {
          discount = item.sub;
        }
      });
      this.flag = !this.flag;
      // 直接调用mapMutation中的方法
      this.addToCar({
        id: this.id,
        count: this.selectedCount,
        selected: true,
        price: this.goodsinfo.sell_price,
        discount: discount,
        useStatusList: this.useStatusList,
      });
    },
    // 首先先得到该用户对当前业务的喜欢的情况
    getMyLike() {
      this.$http
        .get("/getMyLikeByWorkId", {
          params: {
            username: this.username,
            work_id: this.id,
          },
        })
        .then((res) => {
          if (res.data.errcode === 200) {
            const data = res.data.message;
            if (data.length > 0) {
              this.likeId = data[0].id;
              this.isLiked = true;
            }
          } else {
            this.isLiked = false;
          }
        });
    },
    changeLike() {
      this.isLiked = !this.isLiked;
      if (this.isLiked) this.addMyLike();
      else {
        this.cancelMyLike();
      }
    },
    // 添加喜欢
    addMyLike() {
      let params = {
        type: 3,
        username: this.username,
        work_id: this.goodsinfo.id,
        title: this.goodsinfo.title,
        content: this.goodsinfo.zhaiyao,
        price: this.goodsinfo.sell_price,
        img: this.goodsinfo.img_url,
      };
      this.$http.post("/addMyLike", params).then((res) => {
        if (res.data.errcode === 200) {
          Toast("成功添加至我的喜欢!!!");
        } else {
          Toast("操作失败!!!");
        }
      });
    },
    // 取消喜欢
    cancelMyLike() {
      let params = {
        id: this.likeId,
      };
      this.$http.post("/delMyLike", params).then((res) => {
        if (res.data.errcode === 200) {
          this.isLiked = false;
          Toast("已取消!!!");
        } else {
          Toast("操作失败!!!");
        }
      });
    },
    beforeEnter(el) {
      // 入场动画开始之前，设置小球的起始状态
      el.style.transform = "translate(0,0)";
    },
    enter(el, done) {
      //transform:变换
      //translate:位移
      //transition:过渡效果
      // 入场动画结束之后，小球的终止状态
      el.offsetWidth;

      // 动态获取小球的横纵坐标，el表示的就是小球
      const ballPos = el.getBoundingClientRect();
      //动态获取徽标的横纵坐标,因为vue父组件向子组件挺麻烦，所以操纵了DOM元素（且与双向数据绑定无关）
      // 操纵DOM的优点：不论要操作的元素属于哪个组件，只要该元素属于document，那么就能获取到。
      const badgePos = document.getElementById("badge").getBoundingClientRect();
      const left = badgePos.left - ballPos.left;
      const top = badgePos.top - ballPos.top;
      el.style.transform = "translate(" + left + "px," + top + "px)";
      // 为了使小球有回弹效果，使用了贝塞尔曲线。贝塞尔生成器：http://cubic-bezier.com/#.46,-0.4,1,.49
      el.style.transition = "all .5s cubic-bezier(.46,-0.4,1,.49)";
      // 手动回调done
      done();
    },
    afterEnter(el) {
      // 入场动画完成之后的回调函数
      this.flag = !this.flag;
    },
    getSelectedCount(c) {
      // 获取选择商品的数量
      // 将用户选择的最新值，保存到data中，方便用户点击加入购物车，把数量加入徽标中
      this.selectedCount = c;
    },
    createOrderNo() {
      let identity = localStorage.getItem("identityResult");
      if (identity == 2) {
        let order_no = "OD" + moment(new Date()).format("YYYYMMDDHHmmss");
        localStorage.setItem("order_no", order_no);
        this.toBuy(order_no);
      } else {
        Toast("请您先登录账号！！！");
      }
    },
    toBuy(order_no) {
      //将购物车的商品添加进入订单表里
      let params = {
        username: this.username,
        order_no: order_no,
        status: 0,
        goods_no: this.goodsinfo.goods_no,
        stock_quantity: this.goodsinfo.stock_quantity,
        sell_price: this.goodsinfo.sell_price,
        number: this.selectedCount,
        img: this.goodsinfo.img_url,
        title: this.goodsinfo.title,
      };
      this.$http.post("/buyAddOrder", params).then((res) => {
        if (res.data.errcode === 200) {
          this.$router.push("/idssp/order/confirmOrder");
        } else {
          Toast("操作失败!!!");
        }
      });
    },
    // 领取优惠券,给这个人添加该券
    getTicket(index, item) {
      this.discountList[index].get = true;
      // 添加到个人优惠券表
      let params = {
        username: this.username,
        goods_id: this.goodsinfo.id,
        discount: item.discount,
        sub: item.sub,
        limit_num: item.limit,
        use_status: 1,
      };
      this.$http.post("/addDiscount", params).then((res) => {
        if (res.data.errcode === 200) {
          Toast("领取成功！！！");
        } else {
          Toast("操作失败!!!");
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.empty-con {
  width: 200px;
  height: 200px;
  background: url("../../assets/img/order/empty.png") no-repeat;
  background-size: 100% 100%;
  background-position-y: center;
  margin: 0 auto;
  text-align: center;
  .empty-text {
    padding-top: 180px;
    font-size: 15px;
  }
}
.ball {
  width: 15px;
  height: 15px;
  background-color: red;
  border-radius: 50%;
  position: absolute; //让小球脱离标准流
  z-index: 99; //让小球叠在页面上
  left: 152px;
  top: 369px;
  // 将来小球通过动画位移的位置
  // transform: translate(86px,252px);
}
.goodsinfo-container {
  background-color: #eee;
  overflow: hidden;
  .discount {
    margin: 10px 0;
    padding: 10px 0;
    border-bottom: 1px solid #ccc;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    .ticket {
      font-weight: bold;
      color: #ff8a9e;
      background-color: #fff0f6;
    }
  }
  .discount-detail {
    width: 377px;
    // height: 200px;
    background-color: #fff;
    padding: 10px 20px;
    .top-con {
      display: flex;
      .title {
        width: 360px;
        font-size: 15px;
        font-weight: bold;
        text-align: center;
      }
    }
    .block {
      margin: 20px 0;
      display: flex;
      // justify-content: space-between;
      .img {
        border-radius: 10px;
        color: white;
        width: 50px;
        height: 50px;
        background-color: #ff8a9e;
        text-align: center;
      }
      .block-detail {
        padding: 10px;
        display: flex;
        justify-content: space-between;
        width: 100%;
        border: 1px solid #ccc;
      }
    }
  }
}
.operate {
  display: flex;
  .my-like-con {
    margin: 7px 0 0 10px;
  }
}
.btnarea {
  flex-direction: column;
  button + button {
    //后一个button
    margin-top: 15px;
  }
}
</style>


// 分析：小球动画有Bug的原因：小球入场动画的终点坐标固定写死了
// 关键是动态得到小球和徽标的横纵坐标，再将其相减即可